﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HPortal.Lib;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.IO;
using CrystalDecisions.CrystalReports.Engine;

namespace HPortal.Backend
{
    public partial class DetaiList : System.Web.UI.Page
    {
        static ReportDocument red;       
        DataTable la, dtReport;        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                loadReport();
            }

            if (!IsPostBack)
            {
                cboLinhvuc.DataSource = DatabaseHelper.Select("Select LinhvucID,Ten From KH_Linhvuc");
                cboLinhvuc.DataTextField = "Ten";
                cboLinhvuc.DataValueField = "LinhvucID";
                cboLinhvuc.DataBind();
                cboLinhvuc.Items.Insert(0, new ListItem("Tất cả", "0"));
                cboLinhvuc.SelectedIndex = 0;
                
                cboLoai.DataSource = DatabaseHelper.Select("Select LoaiID,TenLoai From KH_Loai");
                cboLoai.DataTextField = "TenLoai";
                cboLoai.DataValueField = "LoaiID";
                cboLoai.DataBind();
                cboLoai.Items.Insert(0, new ListItem("Tất cả", "0"));
                cboLoai.SelectedIndex = 0;
                
                cboCap.DataSource = DatabaseHelper.Select("Select CapID,TenCap From KH_Cap");
                cboCap.DataTextField = "TenCap";
                cboCap.DataValueField = "CapID";
                cboCap.DataBind();
                cboCap.Items.Insert(0, new ListItem("Tất cả", "0"));
                cboCap.SelectedIndex = 0;

                cboNam.DataSource = DatabaseHelper.Select("Select Distinct Nam From KH_Tiendo ORDER BY Nam DESC");
                cboNam.DataTextField = "Nam";
                cboNam.DataValueField = "Nam";
                cboNam.DataBind();
                cboNam.Items.Insert(0, new ListItem("Tất cả", "0"));
                cboNam.SelectedIndex = 0;

                cboDonvi.DataSource = DatabaseHelper.Select("Select DonviID,Ten From KH_Donvi ORDER BY Ten DESC");
                cboDonvi.DataTextField = "Ten";
                cboDonvi.DataValueField = "DonviID";
                cboDonvi.DataBind();
                cboDonvi.Items.Insert(0, new ListItem("Tất cả", "0"));
                cboDonvi.SelectedIndex = 0;
            }            
        }

        private void grvManager_DataBind()
        {         
            la = new DataTable();
            la = DatabaseHelper.Select("Exec [KH_TimkiemDetaiTheoNguoidung] " + DatabaseHelper.EscapeQuote(txtKeyword.Text) + "," + cboLinhvuc.SelectedValue + "," + cboLoai.SelectedValue + "," + cboCap.SelectedValue + "," + cboNam.SelectedValue + "," + cboDonvi.SelectedValue + "," + cboTrangthai.SelectedValue + "," + isNVVuKHCNMT() + "," + this.Context.User.Identity.Name);
            this.grvLargeArticle.DataSource = la;
            grvLargeArticle.DataBind();
        }

        protected void cmdSearch_Click(object sender, EventArgs e)
        {
            this.CrystalReportViewer1.Visible = false;
            this.grvLargeArticle.Visible = true;
            grvManager_DataBind();
        }

        private Boolean isNVVuKHCNMT()
        {
            String VuKHCNRole = System.Configuration.ConfigurationManager.AppSettings["VuKHCNRole"].ToString();
            if (this.Context.User.Identity.IsAuthenticated)
            {
                string[] arrRoleName = Roles.GetRolesForUser(this.Context.User.Identity.Name);
                foreach (string roleName in arrRoleName)
                    if(roleName==VuKHCNRole)
                        return true;
            }
            return false;
        }

        protected void grvLargeArticle_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvLargeArticle.PageIndex = e.NewPageIndex;
            grvManager_DataBind();
        }

        public static void ExportToSpreadsheet(DataTable table, string name)
        {
            HttpContext context = HttpContext.Current;

            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = table;
            GridView1.DataBind();

            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.AddHeader("content-disposition",
             "attachment;filename=" + name + ".xls");
            context.Response.Charset = "";
            context.Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }

            GridView1.RenderControl(hw);
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            context.Response.Write(style);
            context.Response.Output.Write(sw.ToString());
            context.Response.Flush();
            context.Response.End();
        }

        protected void cmdExport_Click(object sender, EventArgs e)
        {
            DataTable la = DatabaseHelper.Select("Exec [KH_TimkiemDetaiTheoNguoidung] " + DatabaseHelper.EscapeQuote(txtKeyword.Text) + "," + cboLinhvuc.SelectedValue + "," + cboLoai.SelectedValue + "," + cboCap.SelectedValue + "," + cboNam.SelectedValue + "," + cboDonvi.SelectedValue + "," + cboTrangthai.SelectedValue + "," + isNVVuKHCNMT() + "," + this.Context.User.Identity.Name);
            ExportToSpreadsheet(la, "DSDetai");
        }
        
        protected void btnPrint_Click(object sender, EventArgs e)
        {            
            red = null;
            loadReport();
            //Response.Write("<script type='text/javascript'> alert('"+cboReport.SelectedValue+"');</script>");
        }

        private void loadReport()
        {
            this.grvLargeArticle.Visible = false;
            this.CrystalReportViewer1.Visible = true;
            //Response.Redirect("~/Backend/Report/TestReport.aspx");            
            if (red == null)
            {
                red = new ReportDocument();             
                switch (Int32.Parse(cboReport.SelectedValue))
                {
                    case 1:
                        red.Load(Server.MapPath("../Backend/Report/CR_DMDT_NCKH_PTCN.rpt"));
                        break;
                    case 2:
                        red.Load(Server.MapPath("../Backend/Report/CrystalReport2.rpt"));                        
                        break;
                    case 3:
                        red.Load(Server.MapPath("../Backend/Report/CrystalReport2.rpt"));                        
                        break;
                    default: break;                        
                }
                dtReport = new DataTable();
                dtReport = DatabaseHelper.Select("Exec [KH_TimkiemDetaiTheoNguoidung] " + DatabaseHelper.EscapeQuote(txtKeyword.Text) + "," + cboLinhvuc.SelectedValue + "," + cboLoai.SelectedValue + "," + cboCap.SelectedValue + "," + cboNam.SelectedValue + "," + cboDonvi.SelectedValue + "," + cboTrangthai.SelectedValue + "," + isNVVuKHCNMT() + "," + this.Context.User.Identity.Name);
                red.SetDataSource(dtReport);

                if (dtReport.Rows.Count == 0)
                {
                    //Label3.Text = "Không tìm thấy dữ liệu ! Mời bạn chọn lại tiêu chí tìm kiếm !";
                    red = null;
                }
            }
            CrystalReportViewer1.ReportSource = red;
            CrystalReportViewer1.RefreshReport();  
        }
    }
}